﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using SBlogCore.Common.FluentValidatorExtend;
using SBlogCore.Common.Models;

namespace SBlogCore.Common.Filters
{
    [SkipScan]
    public class GlobalActionResultFilter : IAsyncResultFilter
    {

        public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result is not ObjectResult {StatusCode: 400} objResult) 
                return next.Invoke();
            //过滤模型验证的异常
            var jsonRes=JsonConvert.SerializeObject(objResult.Value);
            var res = JsonConvert.DeserializeObject<FluentResponseModel>(jsonRes);
            var resErrors = res?.Errors;
            if (resErrors is {})
            {  
                context.Result=new ObjectResult(ResultEntity<object?>.Error(JsonConvert.SerializeObject(resErrors)));
            }
            return next.Invoke();
        }
    }
}
